package org.java.user.controller;

import org.java.commons.vo.Result;
import org.java.user.api.damain.User;
import org.java.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;

@RestController
@RequestMapping("/user")
public class UserController
     //   implements UserCenter
{
    @Autowired
    private UserService userService;

//    所有人都能访问
    @PermitAll()
    @GetMapping("/load/{name}")
//    @ResponseBody
  //  @Override
    public User loadUserByName(@PathVariable("name") String name) {
        return userService.loadUserByName(name);
    }
    @RolesAllowed("ADMIN")
    @GetMapping
    //page是分页对象
    public Page<User> search(
            // 搜索的关键字，可以通过姓名搜索，或者登录名搜索
            @RequestParam(value = "kw", required = false) String keyword,
            // 当前的页码，Spring Data里面页码从0开始的
            @RequestParam(value = "pn", defaultValue = "0") int pageNumber,
            // 每页显示的记录数
            @RequestParam(value = "ps", defaultValue = "10") int pageSize,
            // 排序的字段
            @RequestParam(value = "ob", required = false) String orderBy,
            // 排序的方向
            @RequestParam(value = "dire", required = false) String direction
    ){
        return this.userService.searchUser(keyword, pageNumber, pageSize, orderBy, direction);
    }

    @RolesAllowed("ADMIN")
    //保存数据(新增)
    @PostMapping
    public Result save(@RequestBody User user){
        return this.userService.save(user);
    }
    //ROLE_是在登录的时候，在roleKey之前固定新增的字符串
    @Secured("ROLE_ADMIN")
    @GetMapping("{id}")
    public User loadById(@PathVariable("id") String id){
        return this.userService.findById(id);
    }
}
